// memoryGuard.ts
export class MemoryGuard {
  private limitBytes: number;
  private inflight = 0;
  private waiters: Array<() => void> = [];

  constructor(limitBytes: number) {
    this.limitBytes = limitBytes;
  }

  async acquire(bytes: number) {
    if (bytes <= 0) return;
    while (this.inflight + bytes > this.limitBytes) {
      await new Promise<void>((r) => this.waiters.push(r));
    }
    this.inflight += bytes;
  }

  release(bytes: number) {
    if (bytes <= 0) return;
    this.inflight = Math.max(0, this.inflight - bytes);
    // 逐个唤醒，避免“惊群”
    const w = this.waiters.shift();
    if (w) w();
  }
}
